/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.liquidByte.trafficMustang.server.dao;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.criteria.*;
import org.liquidByte.trafficMustang.server.dataModel.*;
import org.liquidByte.trafficMustang.server.repository.RastreamentoRepository;

/**
 *
 * @author Alexandre
 */
@Stateless
public class RastreamentoDAO extends PersistableDAO<Rastreamento> implements RastreamentoRepository {

    public RastreamentoDAO() {
        super(Rastreamento.class);
    }

    public Localizacao getLastLocation(Usuario usuario) {
        EntityManager em = this.getEntityManager();
        CriteriaBuilder cb = em.getCriteriaBuilder();
        
        CriteriaQuery<Rastreamento> q = cb.createQuery(Rastreamento.class);
        Root<Rastreamento> root = q.from(Rastreamento.class);
        q.select(root)
         .where(cb.equal(root.get(Rastreamento_.usuario), usuario))
         .orderBy(cb.desc(root.get(Rastreamento_.rastreamentoPK).get(RastreamentoPK_.rastrDt)));
        
        Rastreamento rastr;
        try {
            rastr = em.createQuery(q).setMaxResults(1).getSingleResult();
        } catch (NoResultException e) {
            rastr = null;
        }
        if (rastr == null) {
            return null;
        } else {
            return rastr.getLocalizacao();
        }
    }

}
